﻿using System.Collections.Generic;
using System.Linq;
using RssReader.DataModel;
using RssReader.Feeds;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;

// The User Control item template is documented at http://go.microsoft.com/fwlink/?LinkId=234236

namespace RssReader.Common
{
    public sealed partial class Settings
    {
        private readonly CategoryHelper _categoryHelper = new CategoryHelper();
        private List<Category> _categories;
        public Settings()
        {
            InitializeComponent();

            Bind_categories();
        }

        private void Bind_categories()
        {
            ring.IsActive = true;
            
            _categoryHelper.Get_categories_from_composite_settings(true);
            _categories = _categoryHelper.Categories;
            ItemListView.ItemsSource = _categories;
            ring.IsActive = false;

        }

        private void Toggled(object sender, RoutedEventArgs routedEventArgs)
        {
            var toggleSwitch = sender as ToggleSwitch;

            if (toggleSwitch != null && toggleSwitch.Tag != null)
            {
                var categoryExists =
                    _categories.FirstOrDefault(
                        category => category.Name.ToLower() == toggleSwitch.Tag.ToString().ToLower());

                if (categoryExists != null)
                {
                    categoryExists.Visible = toggleSwitch.IsOn;
                    _categoryHelper.Put_categories(_categories);   
                }
            }
        }

        private void Delete_category(object sender, RoutedEventArgs e)
        {
            var deleteButton = sender as Button;

            if (deleteButton != null && deleteButton.Tag != null)
            {
                var allCategoriesExceptDeleted =
                    _categories.Where(category => category.Name.ToLower() != deleteButton.Tag.ToString().ToLower()).ToList();

                if (allCategoriesExceptDeleted !=null)
                {
                    _categoryHelper.Put_categories(allCategoriesExceptDeleted);
                    ItemListView.ItemsSource = allCategoriesExceptDeleted;
                }
            }
        }
    }
}
